package com.lzh.dlykserver.aspect;

import com.lzh.dlykserver.commons.DataScope;
import com.lzh.dlykserver.constant.Constants;
import com.lzh.dlykserver.entity.TUser;
import com.lzh.dlykserver.query.BaseQuery;
import com.lzh.dlykserver.util.JWTUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Aspect
@Component
public class DataScopeAspect {

    //aspectJ 实现aop
    @Pointcut(value = "@annotation(com.lzh.dlykserver.commons.DataScope)")
    public void pointCut() {

    }

    @Around(value = "pointCut()")
    public Object process(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();

        //拿到方法上的注解
        DataScope dataScope = methodSignature.getMethod().getDeclaredAnnotation(DataScope.class);


        String tableAlias = dataScope.tableAlias();
        String tableField = dataScope.tableField();

        //可以拿到当前请求的request对象
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        String token = request.getHeader(Constants.TOKEN_NAME);

        //从token中解析出是管理员还是普通用户
        TUser tUser = JWTUtils.parseUserFromJWT(token);

        //拿到用户角色
        List<String> roleList = tUser.getRoleList();

        //不包含admin角色,只查当前用户自己的角色
        if (!roleList.contains("admin")) {
            //拿到第一个参数
            Object params = joinPoint.getArgs()[0];
            if (params instanceof BaseQuery) {
                BaseQuery query = (BaseQuery) params;
                query.setFilterSQL(" and " + tableAlias + "." + tableField + "=" + tUser.getId());
            }
        }
        System.out.println("目标方法执行之前....");
        Object result = joinPoint.proceed();
        System.out.println("目标方法执行之后....");
        return result;
    }

}
